package com.simba.server.controllers.impl;

import com.simba.common.jsonserver.JsonChannelManager;
import com.simba.server.commands.impl.web.WebSortInfoCmd;
import com.simba.server.components.*;
import com.simba.server.components.data.SortInfo;
import org.apache.log4j.Logger;


import com.simba.common.log.LogUtil;

import com.simba.server.commands.impl.record.RecordPacketOnCmd;
import com.simba.server.controllers.IPacketOnController;
import org.jboss.netty.channel.Channel;
import org.json.JSONObject;

import java.util.Collections;

public class PacketOnController implements IPacketOnController
{
	private static final Logger logger = Logger.getLogger(PacketOnController.class);

	@Override
	public void onPacketOnMessage(SortInfo sortInfo)
	{
		try
		{
			SortInfoManager.getInstance().addSortInfo(sortInfo);
			this.requestSortInfo(sortInfo);
			this.recordSortResult(sortInfo);
			this.restorePacketOnInfo(sortInfo);
			//美国云途杰哥监控发给
			this.sendToDWSClient(sortInfo);
		}
		catch (Exception ex)
		{
			LogUtil.LogError(PacketOnController.logger, "Handle Packet On Message Error -- Exception : " + ex);
		}
	}

	private void restorePacketOnInfo(SortInfo sortInfo)
	{
		CommandExecutor.executorSqlCommand(RecordPacketOnCmd.NAME, sortInfo,false);
	}

	private void requestSortInfo(final SortInfo sortInfo)
	{
		try
		{
			String barcode = sortInfo.getBarcode().toLowerCase();
			if (barcode.equals("noread"))
			{
				sortInfo.setErrorCodeSVR(SortCommonDefines.ERROR_CODE_3_NO_READ_BARCODE);
			}
			else if (!BarcodeManager.getInstance().checkBarcodeListValid(sortInfo))
			{
				sortInfo.setErrorCodeSVR(SortCommonDefines.ERROR_CODE_4_MULTI_BARCODE);
			}
			else if (!BarcodeManager.getInstance().checkBarcodeValid(barcode))
			{
				sortInfo.setErrorCodeSVR(SortCommonDefines.ERROR_CODE_7_INVALID_BARCODE);
			}
			else
			{
				sortInfo.doSetUploadFlag();
				boolean res = CommandExecutor.executorWebCommand(WebSortInfoCmd.NAME, sortInfo,true);
				if (!res)
				{
					LogUtil.LogError(logger,
							"[WebSortInfoError] billCode : [" + sortInfo.getBarcode() + "] errorCode : [" + sortInfo.getErrorCodeSVR() + "]");
				}
			}

			SortInfoManager.getInstance().handleSortInfoResult(sortInfo);

			Collections.sort(sortInfo.getSlotsList());
		}
		catch (Exception ex)
		{
			LogUtil.LogError(logger, "Request Sort Info Error -- Exception : " + ex);
		}
	}

	private void recordSortResult(SortInfo sortInfo)
	{
		try
		{
			StringBuilder info = new StringBuilder();

			info.append("[Key:WheelPacketOnDecoder],");
			info.append("[SorterID:").append(sortInfo.getSorterId()).append("],");
			info.append("[Barcode:").append(sortInfo.getBarcode()).append("],");
			info.append("[BarcodeList:").append(sortInfo.getBarcodeList()).append("],");
			info.append("[PlcID:").append(sortInfo.getPlcId()).append("],");
			info.append("[ErrorCode:").append(sortInfo.getErrorCodeSVR()).append("]");
			info.append("[SlotsList:").append(sortInfo.getSlotsList()).append("]");
			info.append("[Weight:").append(sortInfo.getWeight()).append("]");

			String content = info.toString();

			LogUtil.LogDebug(logger, content);
		}
		catch (Exception ex)
		{
			LogUtil.LogError(logger, "[PacketOffDecoder.recordSortResult] Error:" + ex.getMessage());
		}

	}
	private void sendToDWSClient(SortInfo wheelSortInfo) {
		JSONObject sendObj = new JSONObject();
		sendObj.put("ServiceName", "LinePacketOn");
		sendObj.put("SorterID", wheelSortInfo.getSorterId());
		sendObj.put("sortKey", wheelSortInfo.getSortingId());
		sendObj.put("barcode", wheelSortInfo.getBarcode());
		sendObj.put("responseBarcode", wheelSortInfo.getBarcode());
		sendObj.put("weight", String.valueOf(wheelSortInfo.getWeight()));
		sendObj.put("length", String.valueOf(wheelSortInfo.getLength()));
		sendObj.put("width", String.valueOf(wheelSortInfo.getWidth()));
		sendObj.put("height", String.valueOf(wheelSortInfo.getHeight()));
		sendObj.put("volume", String.valueOf(wheelSortInfo.getVolume()));
		sendObj.put("serverSlot", wheelSortInfo.getSlotsList().toString());
		sendObj.put("serverMsg", "success");
        LogUtil.LogInfo(logger,"发给监控"+sendObj.toString());
		Channel[] channels = JsonChannelManager.getInstance().getChannelList();

		for (Channel tmpChannel : channels) {
			if (tmpChannel == null) {
				continue;
			}
			JsonChannelManager.getInstance().commitResponse(tmpChannel, sendObj.toString().getBytes(), false);
		}


	}
}
